package com.web.boot.web.base;

import com.blue.core.dict.HttpMethod;
import com.blue.core.dict.annotation.DictParser;
import com.blue.http.annotation.Http;
import com.blue.http.message.HttpRequest;
import com.blue.http.message.View;
import com.blue.jdbc.Page;
import com.blue.validation.group.SaveModel;
import com.web.core.async.redis.CacheRefreshSender;
import com.web.core.base.model.Config;
import com.web.core.base.service.ConfigService;
import com.web.core.util.Const;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

@Controller
@Http(url = "/base")
public class ConfigController
{
	@Resource
	private ConfigService configService;
	@Resource
	private CacheRefreshSender cacheRefreshSender;
	
	private DictParser dictParser = DictParser.getInstance();
	
	public ConfigController()
	{
	}
	
	@Http(url = "/config_list", method = HttpMethod.GET)
	public View listGet(HttpRequest request)
	{
		Config config = request.getQueryObject(Config.class);
		return View.createBuilder().setView("/base/config_list")
				.put("page", configService.list(config, null))
				.put("model", config)
				.put("map", dictParser.getStringMap())
				.build();
	}
	
	@Http(url = "/config_list", method = HttpMethod.POST)
	public View listPost(HttpRequest request)
	{
		Config config = request.getPostObject(Config.class);
		Page<Config> page = new Page<>(Const.PAGE_SIZE);
		page.setCurPage(request.getPostInt("start", Const.PAGE_START));
		return View.createBuilder().setView("/base/config_list_grid")
				.put("page", configService.list(config, page))
				.build();
	}
	
	@Http(url = "/config_get", method = HttpMethod.GET)
	public View get(HttpRequest request)
	{
		Config config = request.getQueryObject(Config.class);
		if (config.getId() != null)
		{
			config = configService.get(config.getId());
		}
		return View.createBuilder().setView("/base/config_get")
				.put("model", config)
				.put("map", dictParser.getStringMap())
				.build();
	}
	
	@Http(url = "/config_save", method = HttpMethod.POST)
	public void save(HttpRequest request)
	{
		Config config = request.getPostObject(Config.class, SaveModel.class);
		configService.save(config);
		cacheRefreshSender.send(CacheRefreshSender.CONFIG_CACHE, config.getId());
	}
	
	@Http(url = "/config_refresh", method = HttpMethod.POST)
	public void refresh(HttpRequest request)
	{
		cacheRefreshSender.send(CacheRefreshSender.CONFIG_CACHE);
	}
	
}
